package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.WxLoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.WxTokenService;
import com.ruoyi.task.domain.TaskUser;
import com.ruoyi.task.service.ITaskUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxTokenService wxTokenService;

    @Autowired
    private ITaskUserService iTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        /*LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }*/

        if( wxTokenService.getToken(request) == null){
            System.out.println("管理员用户");
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }else{
            System.out.println("微信用户");
            WxLoginUser wxUser = wxTokenService.getWxUser(request);
            if (wxUser == null) {
                System.out.println("请重新登录1");
                String msg = StringUtils.format("请求访问：{}，请重新登录", request.getRequestURI());
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("401", msg,0)));
                return; // 终止过滤链
            }
           // wxTokenService.verifyToken(wxUser);
            TaskUser taskUser = iTokenService.selectTaskUserById(wxUser.getUserId());
            if (taskUser == null) {
                System.out.println("请重新登录2");
                String msg = StringUtils.format("请求访问：{}，请重新登录", request.getRequestURI());
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("401", msg,0)));
                return; // 终止过滤链
            }

           /* System.out.println("微信用户 --- "+  wxUser.getType());
            if ( wxUser.getType() == 1 || wxUser.getType() == 2 ) {
               *//* HospitalNursingStaff hospitalNursingStaff = iHospitalNursingStaffService.selectHospitalNursingStaffByNursingStaffId(wxUser.getUserId());
                if (hospitalNursingStaff.getState().equals("2")){
                    String msg = StringUtils.format("请求访问：{}，该账号已经解聘不能登录", request.getRequestURI());
                    ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("401", msg)));
                    return; // 终止过滤链
                }*//*
            }*/
            if (StringUtils.isNotNull(wxUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                wxTokenService.verifyToken(wxUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(wxUser, null, null);
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }
        chain.doFilter(request, response);
    }
}
